#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include<semaphore.h>

#include "list.h"
#include "menu.h"
#include "playcontrl.h"
#include "songlrc.h"

extern Song *pnow;//pnow声明使用main.c中的pnow
int inflag = 0;//主线程进入，暂停歌曲标志
int pauseflag = -1;//暂停标志
int pthreadcls = 0;//主线程退出标志
int chunmusic = 0;
//int chgsongflag = 0;//切歌标志
extern int fd[2];//无名管道
extern sem_t sem;//信号量

char lrcpath[100] = "/home/hhb/Music/YUI-again.lrc";//lrc文件路径名，程序启动默认为第一首歌的lrc
													//每当pnow改变,lrcpath就去改变

void mp3_lrc()//将mp3后缀改成lrc
{
	strcpy(lrcpath,pnow->path);
	lrcpath[strlen(lrcpath) - 3] = 'l';
	lrcpath[strlen(lrcpath) - 2] = 'r';
	lrcpath[strlen(lrcpath) - 1] = 'c';
}

int contrlmenu()//总菜单
{
	int x;
	printf("\t\t\t      Mplayer\n");
	printf("\t\t\t********************\n");
	printf("\t\t\t     1.点歌\n");
	printf("\t\t\t     2.暂停/播放\n");
	printf("\t\t\t     3.上一首\n");
	printf("\t\t\t     4.下一首\n");
	printf("\t\t\t     5.快进\n");
	printf("\t\t\t     6.快退\n");
	//printf("\t\t\t     7.退出mplayer\n"); //后期删除选项7
	printf("\t\t\t     0.返回上一级\n");
	printf("\t\t\t********************\n");

	Song *p = read_song();
	if(p == NULL)
	{
		getchar();
		printf("文件中还没有歌曲,请去添加\n");
		printf("请按回车返回\n");
		getchar();
		return 0;
	}

	printf("**********************\n");
	while(p->next != NULL)
	{
		printf("%04d,%s\n",p->songid,p->path);
		p = p->next;
	}
	printf("**********************\n");
	//getchar();

	printf("please select:\n");
	scanf("%d",&x);
	while(x<0 || x>6)
	{
		printf("input error,again:\n");
		scanf("%d",&x);
	}
	return x;
}

int volumemenu()//音量菜单
{
	int x;
	printf("\t\t\t      Mplayer\n");
	printf("\t\t\t********************\n");
	printf("\t\t\t     1.静音\n");
	printf("\t\t\t     2.取消静音\n");
	printf("\t\t\t     3.调节音量\n");
	printf("\t\t\t     0.返回上一级\n");
	printf("\t\t\t********************\n");
	//getchar();
	printf("please select:\n");
	scanf("%d",&x);
	while(x<0 || x>3)
	{
		printf("input error,again:\n");
		scanf("%d",&x);
	}
	return x;
}

int playsong()//点歌函数
{
	int x,flag = 0;
	char buf[100] = {0};
	Song *p = read_song();
	//pnow = read_song();
	printf("请输入要播放歌曲的序号\n");
	scanf("%d",&x);

	while(p != NULL)
	{
		if(p->songid == x)
		{
			pnow = p;
			mp3_lrc();
			//printf("%s\n",pnow->path);
			//getchar();
			strcpy(buf,"loadfile ");
			strcat(buf,p->path);
			strcat(buf,"\n");

			//printf("%s\n",pnow->path);
			//getchar();
			flag = 1;
			break;
		}
		p = p->next;
	}
	if(flag == 0)
	{
		getchar();
		printf("歌单内没有此序号的歌\n");
		printf("按回车返回\n");
		getchar();
		return 0;
	}
	int fp = open("pipe",O_WRONLY | O_NONBLOCK);
	write(fp,buf,strlen(buf));
	close(fp);
	sleep(1);
	if(pauseflag == 1)
		pauseflag = -pauseflag;
	chunmusic = 0;
	return 0;
}

int pausesong()//暂停歌曲函数
{
	//char buf[100];
	int fp = open("pipe",O_WRONLY | O_NONBLOCK);
	//printf("please input existd songpath:\n");
	//scanf("%s",buf);
	//strcat(buf,"\n");
	char buf[5] = "p\n";
	write(fp,buf,strlen(buf));
	pauseflag = -pauseflag;
	close(fp);
	return 0;
}

int nextsong()//下一首歌
{
	Song *p = read_song();
	while(p != NULL)
	{
		if(strcmp(p->path,pnow->path) == 0)
		{
			
			if(p->next == NULL)
			{
				//printf("bbbbbbbbbbbbbbbbbbbbbbbbbb\n");
				pnow = read_song();
				mp3_lrc();
				break;
			}
			pnow = p->next;
			//printf("aaaaaaaaaaaaaaaaaaaaaaaaaaa\n");
			mp3_lrc();
			break;
		}
		p = p->next;
	}
	char buf[100] = {0};
	strcpy(buf,"loadfile ");
	strcat(buf,pnow->path);
	strcat(buf,"\n");
	//strcat(buf,"\n");
	int fp = open("pipe",O_WRONLY | O_NONBLOCK);
	write(fp,buf,strlen(buf));
	if(pauseflag == 1)
	{
		sleep(1);
		pauseflag = -pauseflag;
	}
	close(fp);
	chunmusic = 0;
	return 0;
}

int lastsong() //上一首歌
{
	int flag = 0;
	Song *p = read_song();
	while(p->next != NULL)
	{
		if((pnow->songid -1) == 0)
		{
			break;
		}
		if(p->songid == (pnow->songid -1))
		{
			pnow = p;
			mp3_lrc();
			flag = 1;
			break;
		}
		p = p->next;
	}
	//printf("%d\n",flag);
	if(flag == 0)
	{
		getchar();
		printf("目前播放的已经是第一首歌\n");
		printf("回车继续操作\n");
		getchar();
		return 0;
	}
	char buf[100] = {0};
	strcat(buf,"loadfile ");
	strcat(buf,pnow->path);
	strcat(buf,"\n");

	int fp = open("pipe",O_WRONLY | O_NONBLOCK);
	write(fp,buf,strlen(buf));
	if(pauseflag == 1)
		pauseflag = -pauseflag;
	close(fp);
	chunmusic = 0;
	return 0;
}

void exitsong() //退出mplayer,程序退出调用atexit函数
{
	int fp = open("pipe",O_WRONLY | O_NONBLOCK);
	//printf("please input existd songpath:\n");
	//scanf("%s",buf);
	//strcat(buf,"\n");
	char buf[5] = "q\n";
	write(fp,buf,strlen(buf));
	close(fp);
}

int fastsong()//快进
{
	int t;
	printf("请输入想快进的秒数:\n");
	scanf("%d",&t);

	int fp = open("pipe",O_WRONLY | O_NONBLOCK);
	char buf[10] = {0};
	//char a[6] = "seek ";
	sprintf(buf,"%s%d","seek ",t);
	strcat(buf,"\n");
	write(fp,buf,strlen(buf));
	if(pauseflag == 1)
		pauseflag = -pauseflag;
	close(fp);
	//sleep(1.5);
	return 0;
}

int slowsong()//快退
{
	int t;
	printf("请输入想快退的秒数:\n");
	scanf("%d",&t);
	t = -t;
	int fp = open("pipe",O_WRONLY | O_NONBLOCK);
	char buf[10] = {0};
	//char a[6] = "seek ";
	sprintf(buf,"%s%d","seek ",t);
	strcat(buf,"\n");
	write(fp,buf,strlen(buf));
	if(pauseflag == 1)
		pauseflag = -pauseflag;
	close(fp);
	return 0;
}

int novolume()//静音
{
	int fp = open("pipe",O_WRONLY | O_NONBLOCK);
	char buf[9] = "mute 1\n";
	write(fp,buf,strlen(buf));
	if(pauseflag == 1)
		pauseflag = -pauseflag;
	close(fp);
	return 0;
}

int havevolume()//取消静音
{
	int fp = open("pipe",O_WRONLY | O_NONBLOCK);
	char buf[9] = "mute 0\n";
	write(fp,buf,strlen(buf));
	if(pauseflag == 1)
		pauseflag = -pauseflag;
	close(fp);
	return 0;
}

int changevolume()//改变音量
{
	int x;
	printf("请输入音量大小(0~100):\n");
	scanf("%d",&x);

	int fp = open("pipe",O_WRONLY | O_NONBLOCK);
	char buf[20] = {0};
	//char a[6] = "seek ";
	sprintf(buf,"%s%d%s","volume ",x," 1");
	strcat(buf,"\n");
	write(fp,buf,strlen(buf));
	if(pauseflag == 1)
		pauseflag = -pauseflag;
	close(fp);
	return 0;
}

void *getcmd_thread(void *arg) //线程1：给有名管道发送命令（实现暂停等功能）
{
	//atexit(exitsong);
	//sleep(1);        //睡一秒，把第一首歌打开的歌曲信息刷掉
	//pthread_detach(pthread_self());
	pausesong();
	inflag = 1;
	int x,loop = 1;
	while(loop)
	{
		system("clear");
		x = mainmenu();
		switch(x)
		{
			case 1:
				songsheet(); //歌单操作
				break;
			case 2:
				playcontrl();
				//pthread_create(&tid1,NULL,playcontrl,NULL);
				break;
			case 3:
				volumecontrl();
				break;
			case 0:
			default:
				pthreadcls = 1;	
				//if(pauseflag == 1)
					//pausesong();
				loop = 0;
				break;
 		}
 	}

	return NULL;
}

void playcontrl()//播放控制
{
	int x,loop = 1;
	pnow = read_song();

	while(loop)
	{
		system("clear");
		printf("播放控制\n");
		x = contrlmenu();
		//playsong();
		switch(x)
		{
			case 1:
				playsong();
				//sleep(1);
				//getchar();
				break;
			case 2:
				pausesong();
				//getchar();
				break;
			case 3:
				lastsong();
				//sleep(1);
				break;
			case 4:
				nextsong();
				//sleep(1);
				break;
			case 5:
				fastsong();
				//sleep(1);
				break;
			case 6:
				slowsong();
				//sleep(1);
				break;
			//case 7:
				//exitsong();
				//sleep(1);
				//break;
			case 0:
			default:
				loop = 0;
				break;
		}
	}
}

void volumecontrl()//音量控制菜单
{
	int x,loop = 1;
	while(loop)
	{
		system("clear");
		printf("音量控制\n");
		x = volumemenu();
		//playsong();
		switch(x)
		{
			case 1:
				novolume();
				//sleep(2);
				//getchar();
				break;
			case 2:
				havevolume();
				//sleep(2);
				//getchar();
				break;
			case 3:
				changevolume();
				//sleep(2);
				break;
			case 0:
			default:
				loop = 0;
				break;
		}
	}
}

//get_file_name\nget_time_length\n
void *sndfd_thread(void *arg)  //线程2：给有名管道发送命令，让mplayer返回信息 
{
	//sleep(1);
	int fd = 0;
	char str[50] = "get_time_pos\nget_percent_pos\n";
	while(inflag == 0)
	{
		sleep(1);
	}
	while(1)
	{
		sem_wait(&sem);
		while(pauseflag == 1 || pthreadcls == 1)
		{
			if(pthreadcls == 1)
			{
				sem_post(&sem);
				return NULL;
			}
			sleep(1);
		}
		//if(pthreadcls == 1)
			//break;
		fd = open("pipe",O_WRONLY | O_NONBLOCK);
		if(fd < 0)
		{
			perror("open fifo error\n");
			printf("回车继续操作\n");
			getchar();
			return 0;
		}
		write(fd,str,strlen(str));
		close(fd);
		sem_post(&sem);
		sleep(1);
	}

	return NULL;
}

void *readfd_thread(void *arg)  //读取mplayer发回的信息，保存到buf
{
	int ret;
	//sleep(1);
	//char msg_buf[100] = {0};
	char buf[100] = {0};
	while(1)
	{
		sem_wait(&sem);
		while(pauseflag == 1 || pthreadcls == 1)
		{
			if(pthreadcls == 1)
			{
				sem_post(&sem);  //因为此线程会先进入，使信号量减1，但是若在暂停时退出，
				                //发送命令线程会因信号量阻塞而卡着，所以这里一定要在退出线程前进行加1操作
				return NULL;
			}
			sleep(1);
		}
		//if(pthreadcls == 1) //暂停的时候退出的话，该线程还在沉睡，所以按0不会退出主程序，这个地方后续需要修改
			//break;
		ret = read(fd[0],buf,sizeof(buf));
		
		if(ret > 0)
		{
			buf[100] = '\0';
			//printf("********************%s\n",buf);
			//mp3_lrc();
			deal_data(buf);
			memset(buf,0,sizeof(buf));
		}
		sem_post(&sem);
		sleep(1);
	}

	return NULL;
}

void deal_data(char *buf)  //解析buf中的信息，拿到要用的
{
	char msg_buf[100] = {0};
	char *p = NULL;
	char *ps = NULL;
	//char lrcpath[100] = {0};
	struct lrc *head = NULL;

	strcpy(msg_buf,buf);

	p = strtok(msg_buf,"\n");
	while(p != NULL)
	{
		ps = strstr(p,"=");
		if(strstr(p,"ANS_TIME_POSITION") != NULL)
		{
			//printf("time:%s\n",ps+1);
			if(chunmusic == 0)
			{
				head = GetLrc(lrcpath);
				while(head != NULL)
				{
					if(atoi(ps+1) == head->time)
					{
						printf("%s\n",head->lrctext);
						//memset(lrcpath,0,sizeof(lrcpath));
						//head = NULL;
						break;
					}
					head = head->next;
				}
			}
		}
		else if(strstr(p,"ANS_PERCENT_POSITION") != NULL)
		{
			//printf("percent:%s\n",ps+1);
			if(strcmp(ps+1,"99") == 0)
			{
				sleep(2);
				printf("歌曲即将结束，自动播放下一首歌...\n");
				nextsong();
			}
		}
		p = strtok(NULL,"\n");
	}
	memset(msg_buf,0,sizeof(msg_buf));
}

